//
//  BIDAddFavorableInfoViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/12.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDAddFavorableInfoViewController.h"
#import "BIDBrowserImageViewController.h"
#import "ELCImagePickerHeader.h"
#import "BIDCustomTextView.h"
#import "BIDAddPhotoView.h"
#import "BIDUploadFile.h"

#import <MobileCoreServices/UTCoreTypes.h>
//发布优惠信息
static NSString *publishFavorableInfoURL = @"preferentialAndroid/add.action";

@interface BIDAddFavorableInfoViewController ()<BIDAddPhotoViewDelegate, ELCImagePickerControllerDelegate, UINavigationControllerDelegate, BIDUploadFileDelegate>
{
    BIDUploadFile *_uploadFile;
}

@end

@implementation BIDAddFavorableInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"优惠信息";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(closeHandler)];
    _contentTextView.inputAccessoryView = self.toolBar;
    _contentTextView.placeholder = @"请填写发布的信息";
    //
    _addPhotoView.delegate = self;
    //
    _uploadFile = [[BIDUploadFile alloc] initWithURL:[[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], publishFavorableInfoURL]];
    _uploadFile.delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)closeHandler
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

//发布优惠信息
- (IBAction)publishFavorableInfoHandler:(id)sender
{
    NSString *strContent = _contentTextView.text;
    if(strContent.length == 0)
    {
        [self showAlertView:@"请填写要发布的内容" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
    }
    else
    {
        if(_addPhotoView.imgArr.count > 0)
        {
            [_uploadFile addData:@"memberId" value:[AppDelegate getUserId]];
            [_uploadFile addData:@"preferential.type" value:@"2"];
            [_uploadFile addData:@"preferential.title" value:strContent];
            NSUInteger count = 0;
            for(UIImage *img in _addPhotoView.imgArr)
            {
                count++;
                NSData *imgData = UIImageJPEGRepresentation(img, 0.5f);
                NSString *strFileName = [[NSString alloc] initWithFormat:@"fileName%ld.jpg", count];
                [_uploadFile addFileFromMemory:strFileName fieldName:@"fileUploads" data:imgData];
                [_uploadFile addData:@"fileUploadsFileName" value:strFileName];
            }
            [_uploadFile finishAddFile];
            [_uploadFile startUpload];
        }
        else
        {
            NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], publishFavorableInfoURL];
            NSMutableString *strPost = [NSMutableString string];
            [strPost appendFormat:@"memberId=%@", [AppDelegate getServerAddr]];
            [strPost appendFormat:@"&preferential.type=%@", @2];
            [strPost appendFormat:@"&preferential.title=%@", strContent];
            [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
                if(errMsg)
                {
                    [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
                }
                else
                {
                    [self showAlertView:@"发布信息成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler"];
                }
            }];
        }
    }
}

- (void)alertViewHandler
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - BIDAddPhotoViewDelegate
- (void)choosePhoto
{
    if(_addPhotoView.imgArr.count == 3)
    {
        [self showAlertView:@"最多选择3张图片" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    //
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    
    //3-_addPhotoView.imgArr.count
    elcPicker.maximumImagesCount = 111; //Set the maximum number of images to select to 100
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
    elcPicker.mediaTypes = @[(NSString *)kUTTypeImage]; //Supports image and movie types((NSString *)kUTTypeMovie)
    
    elcPicker.imagePickerDelegate = self;
    
    [self presentViewController:elcPicker animated:YES completion:nil];
}

- (void)showPhotoAtIndex:(NSInteger)index withImgArr:(NSArray *)arr
{
    BIDBrowserImageViewController *vc = [[BIDBrowserImageViewController alloc] init];
    vc.index = index;
    vc.imgArr = arr;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)resizeViewWithFrame:(CGRect)frame
{
    _heightForAddPhotoViewConstraint.constant = CGRectGetHeight(frame);
    _heightForContainerViewConstraint.constant = CGRectGetMaxY(frame) + 8;//CGRectGetMinY(_addPhotoView.frame)+CGRectGetHeight(frame)+8;
    //[self.view layoutIfNeeded];
    CGSize contentSize = _scrollView.contentSize;
    contentSize.height = CGRectGetHeight(_containerView.frame);
    [_scrollView setContentSize:contentSize];
}

#pragma mark - BIDUpladFileDelegate
- (void)finishUploadWithResult:(id)obj
{
    if([obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dic = (NSDictionary *)obj;
        NSNumber *value = dic[@"head"][@"success"];
        if([value intValue] == 1)
        {
            [self showAlertView:@"提交成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler"];
        }
        else
        {
            [self showAlertView:@"提交失败" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
    }
}

- (void)uploadFailedWithError:(NSError *)err
{
    [self showAlertView:[err localizedDescription] buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
}

#pragma mark - ELCImagePickerControllerDelegate Methods

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
    for (NSDictionary *dict in info)
    {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                [_addPhotoView addPhoto:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else
        {
            NSLog(@"Uknown asset type");
        }
    }
    //_chosenImgArr = images;
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
